﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Tb.App.API.Applications.Command;
using Tb.App.API.Applications.Command.Basic;
using Tb.App.API.Applications.DTOs;
using Tb.App.API.Dtos.Rabbit;
using Tb.App.ErrorCode;

namespace Tb.App.API.Controllers.Rabbit
{
    /// <summary>
    /// 导出Excel控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    
    public class ExportController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ExportController> logger;
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mediator">中介者</param>
        public ExportController(ILogger<ExportController> logger,IMediator mediator)
        {
            this.logger = logger;
            this.mediator = mediator;
        }
        /// <summary>
        /// 查询基本信息分页
        /// </summary>
        /// <param name="request">命令</param>
        /// <returns>返回查询任务</returns>
        [HttpGet]
        public async Task<ApiResult<ApiPaging<List<BasicDTO>>>> BasicPageQuery([FromQuery] GetBasicQueryCommand request)
        {
            return await mediator.Send(request);
        }
        #region 导出Excel(当前页的数据)
        /// <summary>
        /// 导出Excel(当前页的数据)
        /// </summary>
        /// <param name="request">命令</param>
        /// <returns>返回导出任务</returns>
        [HttpGet]
        public async Task<ApiResult<string>> ExportExcel([FromQuery] GetBasicQueryCommand request)
        {
            try
            {
                logger.LogInformation("导出溯源基本信息操作");
                //if (request.PageSize <= 40) request.PageSize = 1000;
                var result = new ApiResult<string>();
                var list = await BasicPageQuery(request);
                //开始配置导出
                //创建wookbook
                IWorkbook wb=new XSSFWorkbook();
                //创建sheet
                ISheet sheet=wb.CreateSheet("溯源信息");
                //创建第一行
                IRow row=sheet.CreateRow(0);
                row.Height = 40 * 20;
                row.CreateCell(0).SetCellValue("溯源基本信息");
                //合并单元格
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 7));

                
                IRow row1 = sheet.CreateRow(1);
                //创建单元格并赋值
                row1.CreateCell(0).SetCellValue("编号");
                row1.CreateCell(1).SetCellValue("商品名称");
                row1.CreateCell(2).SetCellValue("生产批次");
                row1.CreateCell(3).SetCellValue("保质期");
                row1.CreateCell(4).SetCellValue("生产许可证号");
                row1.CreateCell(5).SetCellValue("生产企业");
                row1.CreateCell(6).SetCellValue("封面图");
                row1.CreateCell(7).SetCellValue("信息完善度");

                //循环添加数据
                var index = 2;
                foreach (var item in list.Data.Data)
                {
                    row1 = sheet.CreateRow(index);
                    row1.CreateCell(0).SetCellValue(item.Id.ToString());
                    row1.CreateCell(1).SetCellValue(item.StoreName);
                    row1.CreateCell(2).SetCellValue(item.Batch);
                    row1.CreateCell(3).SetCellValue(item.Expiration.ToString());
                    row1.CreateCell(4).SetCellValue(item.License);
                    row1.CreateCell(5).SetCellValue(item.Company);
                    row1.CreateCell(6).SetCellValue(item.Picture);
                    row1.CreateCell(7).SetCellValue(item.Completeness.ToString());
                    index++;
                }
                //导出Excel
                byte[] buffer;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                //文件导出
                string _uploadFolder = "wwwroot/export";
                if (!Directory.Exists(_uploadFolder))
                {
                    Directory.CreateDirectory(_uploadFolder);
                }
                //保存文件到服务器
                var fileName = $"溯源基本信息_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                _uploadFolder = Path.Combine(_uploadFolder, fileName);
                using (var fs = new FileStream(_uploadFolder, FileMode.Create, FileAccess.Write))
                {
                   fs.Write(buffer, 0, buffer.Length);
                }
                result.Code = ApiEnum.查询成功;
                result.Message = ApiEnum.查询成功.ToString();
                result.Data = Request.Scheme + "://" + Request.Host + "/export/" + fileName;
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("=>" + ex.Message);
                throw;
            }
        }
        #endregion

        /// <summary>
        /// 查询溯源信息(根据基本信息连接养殖,屠宰,深加工)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<ApiResult<List<TraceabilityDTO>>> ExportTraceability([FromQuery]ExportTraceabilityCommand request)
        {
            return mediator.Send(request);
        }

    }
}
